package com.yanzhang.servlet;

import com.alibaba.fastjson.JSONArray;
import com.mysql.cj.util.StringUtils;
import com.yanzhang.pojo.Role;
import com.yanzhang.pojo.User;
import com.yanzhang.service.role.RoleService;
import com.yanzhang.service.role.RoleServiceImpl;
import com.yanzhang.service.user.UserService;
import com.yanzhang.service.user.UserServiceImpl;
import com.yanzhang.util.Constants;
import com.yanzhang.util.DBUtil;
import com.yanzhang.util.DateUtil;
import com.yanzhang.util.PageUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户增删改查
 * @author yanzhang
 */
public class UserServlet extends HttpServlet {

    private UserService userService;
    private RoleService roleService;

    public UserServlet () {
        userService = new UserServiceImpl();
        roleService = new RoleServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        System.out.println("method：" + method);
        switch (method) {
            case "checkPassword": {
                checkPassword(req, resp);
                break;
            }
            case "updatePassword": {
                updatePassword(req, resp);
                break;
            }
            case "query": {
                queryUserList(req, resp);
                break;
            }
            case "getRoleList": {
                getRoleList(req, resp);
                break;
            }
            case "checkUser": {
                checkUser(req, resp);
                break;
            }
            case "add": {
                addUser(req, resp);
                break;
            }
            case "view": {
                viewUser(req, resp ,"/jsp/userview.jsp");
                break;
            }
            case "modify": {
                viewUser(req, resp ,"/jsp/usermodify.jsp");
                break;
            }
            case "modifyUser": {
                modifyUser(req, resp);
                break;
            }
            case "deleteUser": {
                deleteUser(req, resp);
                break;
            }
            default: {

                break;
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    /**
     * 校验旧密码
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void checkPassword(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Object userSession = req.getSession().getAttribute(Constants.USER_SESSION);
        String oldPassword = req.getParameter("oldpassword");
        Map<String, Object> resultMap = new HashMap<>();
        if (userSession == null) {
            resultMap.put("result","sessionTimeout");
        } else if (StringUtils.isNullOrEmpty(oldPassword)) {
            resultMap.put("result", "error");
        } else {
            User user = (User) userSession;
            if (oldPassword.equals(user.getUserPassword())) {
                resultMap.put("result", true);
            } else {
                resultMap.put("result", false);
            }
        }
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        writer.write(JSONArray.toJSONString(resultMap));
        writer.close();
    }

    /**
     * 修改密码
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void updatePassword(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Object userSession = req.getSession().getAttribute(Constants.USER_SESSION);
        String newPassword = req.getParameter("newpassword");
        if (userSession != null && !StringUtils.isNullOrEmpty(newPassword)) {
            User user = (User) userSession;
            boolean flag = userService.updatePassword(user.getId(), newPassword);
            if (flag) {
                req.setAttribute("message", "修改密码成功，请退出重新登录");
                //移除session
                req.getSession().removeAttribute(Constants.USER_SESSION);
            } else {
                req.setAttribute("message", "密码修改失败");
            }
        } else {
            req.setAttribute("message", "新密码错误");
        }
        req.getRequestDispatcher("jsp/pwdmodify.jsp").forward(req, resp);
    }

    /**
     * 分页查询
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void queryUserList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Role> roleList = null;
        List<User> userList = null;
        String username = req.getParameter("queryname");
        String tempRole = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");
        int queryRole = 0;
        int pageNo = 1;
        if (tempRole != null && !"".equals(tempRole)) {
            queryRole = Integer.parseInt(tempRole);
        }
        if (pageIndex != null && !"".equals(pageIndex)) {
            pageNo = Integer.parseInt(pageIndex);
        }
        int totalCount = userService.getUserCount(username, queryRole);
        int totalPage = PageUtil.getTotalPage(Constants.PAGE_SIZE, totalCount);
        //控制首页和尾页
        if (pageNo < 1) {
            pageNo = 1;
        } else if (pageNo > totalPage) {
            pageNo = totalPage;
        }

        roleList = roleService.getRoleList();
        userList = userService.getUserList(username, queryRole, pageNo, Constants.PAGE_SIZE);
        req.setAttribute("roleList", roleList);
        req.setAttribute("userList", userList);
        req.setAttribute("queryUserName", username);
        req.setAttribute("queryUserRole", queryRole);
        req.setAttribute("totalPageCount", totalPage);
        req.setAttribute("totalCount", totalCount);
        req.setAttribute("currentPageNo", pageNo);
        req.getRequestDispatcher("/jsp/userlist.jsp").forward(req, resp);
    }

    /**
     * 获取角色列表
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void getRoleList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Role> roleList = roleService.getRoleList();
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        writer.write(JSONArray.toJSONString(roleList));
        writer.close();
    }

    /**
     * 校验用户编码是否存在
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void checkUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String data ="exist";
        String userCode = req.getParameter("userCode");
        User userByCode = userService.getUserByCode(userCode);
        if (userByCode == null) {
            data = "notExist";
        }
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        writer.write(JSONArray.toJSONString(data));
        writer.close();
    }

    /**
     * 新增一个用户
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void addUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userCode = req.getParameter("userCode");
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        Integer gender = Integer.parseInt(req.getParameter("gender"));
        String birthStr = req.getParameter("birthday");
        Date birthday = DateUtil.getDate(birthStr, DateUtil.Time_Zone.SYSTEM);
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        Integer userRole = Integer.parseInt(req.getParameter("userRole"));
        Object userSession = req.getSession().getAttribute(Constants.USER_SESSION);
        User sessionUser = (User) userSession;

        User user = new User();
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setGender(gender);
        user.setBirthday(birthday);
        user.setPhone(phone);
        user.setAddress(address);
        user.setUserRole(userRole);
        user.setCreationDate(new Date());
        user.setCreatedBy(sessionUser.getId());

        if (userService.add(user)) {
            resp.sendRedirect(req.getContextPath() + "/user?method=query");
        } else {
            req.getRequestDispatcher("/jsp/useradd.jsp").forward(req, resp);
        }
    }

    /**
     * 查看用户信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void viewUser(HttpServletRequest req, HttpServletResponse resp, String uri) throws ServletException, IOException {
        int id = Integer.parseInt(req.getParameter("uid"));
        User user = userService.getUserById(id);
        if (user == null) {
            resp.sendRedirect(req.getContextPath() + "/user?method=query");
        } else {
            req.setAttribute("user", user);
            req.getRequestDispatcher(uri).forward(req, resp);
        }
    }

    /**
     * 修改一个用户信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void modifyUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = Integer.parseInt(req.getParameter("uid"));
        User user = userService.getUserById(id);
        String userName = req.getParameter("userName");
        Integer gender = Integer.parseInt(req.getParameter("gender"));
        String birthStr = req.getParameter("birthday");
        Date birthday = DateUtil.getDate(birthStr, DateUtil.Time_Zone.SYSTEM);
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        Integer userRole = Integer.parseInt(req.getParameter("userRole"));
        Object userSession = req.getSession().getAttribute(Constants.USER_SESSION);
        User sessionUser = (User) userSession;

        user.setUserName(userName);
        user.setGender(gender);
        user.setBirthday(birthday);
        user.setPhone(phone);
        user.setAddress(address);
        user.setUserRole(userRole);
        user.setModifyDate(new Date());
        user.setModifyBy(sessionUser.getId());

        if (userService.modifyUser(user)) {
            resp.sendRedirect(req.getContextPath() + "/user?method=query");
        } else {
            req.getRequestDispatcher("/jsp/usermodify.jsp").forward(req, resp);
        }
    }

    /**
     * 删除一个用户
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void deleteUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uid = req.getParameter("uid");
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        if (StringUtils.isNullOrEmpty(uid)) {
            writer.write(JSONArray.toJSONString("notExist"));
        } else {
            try {
                int id = Integer.parseInt(uid);
                if (userService.deleteUserById(id)) {
                    writer.write(JSONArray.toJSONString(true));
                } else {
                    writer.write(JSONArray.toJSONString(false));
                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
                writer.write(JSONArray.toJSONString("notExist"));
            } finally {
                writer.close();
            }
        }
        writer.close();
    }
}
